package cn.uce.cc.srv.utils;

import cn.uce.base.entity.OpenRequest;
import cn.uce.utils.StringUtil;
import org.apache.commons.codec.binary.Base64;

import java.security.MessageDigest;


public class SecurityUtils {

    /**
     * 生成md5字符串
     * @param openRequest
     * @return
     */
    public static String generateOpenMD5(OpenRequest openRequest) {
        String securityStr;
        String charset="utf-8";
        String var1 = openRequest.getAccessKey();
        String var2 = openRequest.getCompCode();
        String var3 = openRequest.getMessageBody();
        String var4 = openRequest.getSecretKey();
        String var5 = openRequest.getTimestamp();
        String var6 = openRequest.getVersion();
        String content = var1+var2+var3+var4+var5+var6;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(content.getBytes(charset));
//            securityStr = new String(Base64.encodeBase64(messageDigest.digest()), WebConstant.COMMONENCODING);
            securityStr = new String(Base64.encodeBase64(messageDigest.digest()), "utf-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("MD5-securityStr:"+securityStr);
        return securityStr;
    }

   /**
    * 获取参数名与参数值的MD5加密字符串
    * @param content
    * @param charset
    * @return
    */
   public static String md5(String content, String charset) {
	   if (StringUtil.isBlank(charset)) {
		   charset="utf-8";
	   }

	   if (StringUtil.isBlank(content)) {
		  return content;
	   }

	   try {
           MessageDigest messageDigest = MessageDigest.getInstance("MD5");
           messageDigest.update(content.getBytes(charset));
           return new String(Base64.encodeBase64(messageDigest.digest()), charset);
       } catch (Exception e) {
           throw new RuntimeException(e);
       }
   }
}
